package com.ubigate.CooknaviHA;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class AssetReader {
	private static final String TAG = "AssetReader";
	
	public static Bitmap getImageFromAsset(Context context, String file) {
		//Log.i(TAG, "open Image : "+file);
		Bitmap bitmap = null;
		AssetManager assetManager = context.getAssets();
		InputStream is = null;
		try {
			is = assetManager.open(file);
			bitmap = BitmapFactory.decodeStream(is);
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());// qwe
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				Log.d(TAG, e.getMessage());
			}
		}		
		
		return bitmap;
	}

	public static Bitmap getImageFromAsset(Activity activity, String file) {
		//Log.i(TAG, "open Image : "+file);
		Bitmap bitmap = null;
		AssetManager assetManager = activity.getAssets();
		InputStream is = null;
		try {
			is = assetManager.open(file);
			bitmap = BitmapFactory.decodeStream(is);
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				Log.d(TAG, e.getMessage());
			}
		}		
		
		return bitmap;
	}
	
	public static String getStringFromAsset(Activity activity, String file) {
		String result = "";
		AssetManager assetManager = activity.getAssets();
		InputStream is = null;
		try {
			is = assetManager.open(file);
			result = convertStreamToString(is);
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				Log.d(TAG, e.getMessage());
			}
		}
		
		return result;
	}
	
	public static String convertStreamToString(InputStream is) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			int i = is.read();
			while (i!=-1) {
				baos.write(i);
				i = is.read();
			}
		} catch (IOException e) {
			Log.d(TAG, e.getMessage());
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				Log.d(TAG, e.getMessage());
			}
		}
		
		return baos.toString();
	}
}
